package middleware

import (
	"gitee.com/lmh912225/goweb-utils/src/ginresult"
	"github.com/gin-gonic/gin"
)

/**
所有的通用错误都由这个中间件处理
http status :400
error code: 40000
msg: 由具体的panic传过来
 */

func ErrorHandleMiddleware() gin.HandlerFunc  {
	return func(context *gin.Context) {
		defer func() {
			if err := recover();err!=nil{

				if customErr,ok := err.(*ginresult.ErrorCustom);ok{
					//ginresult.R(context)(ginresult.C_E_BADREQUEST,"failed",err)(ginresult.ErrorJson)
					errorFunc := func(ctx *gin.Context,v interface{}){
						ctx.JSON(customErr.HttpCode,v)
					}
					ginresult.R(context)(customErr.BusinessCode,"failed",customErr.Err.Error())(errorFunc)
				} else {
					//如果不是自定义的错误类型，继续向上panic
					panic(err)
				}


			}
		}()
		context.Next()
	}
}